package com.qqtech.qquan.order.service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.qqtech.core.common.constant.CoreConst;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.exception.OrderException;
import com.qqtech.core.common.util.ArithUtil;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.dao.BaseDao;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseServiceImpl;
import com.qqtech.qquan.activity.model.ActivityBaseVo;
import com.qqtech.qquan.activity.model.ActivitySignVo;
import com.qqtech.qquan.activity.service.ActivityBaseService;
import com.qqtech.qquan.activity.service.ActivitySignService;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.delivery.dao.DeliveryOrderDao;
import com.qqtech.qquan.delivery.enums.DeliveryOrderStatusDictEnum;
import com.qqtech.qquan.delivery.model.DeliveryOrderVo;
import com.qqtech.qquan.hi.service.HiOrderService;
import com.qqtech.qquan.homemaking.service.HomemakingOrderService;
import com.qqtech.qquan.idle.service.IdleBaseService;
import com.qqtech.qquan.mall.enums.MallShopStyleDictEnum;
import com.qqtech.qquan.mall.enums.MallShopTypeDictEnum;
import com.qqtech.qquan.mall.model.MallProduct;
import com.qqtech.qquan.mall.model.MallShop;
import com.qqtech.qquan.mall.model.MallSupplier;
import com.qqtech.qquan.mall.model.MallSupplierUser;
import com.qqtech.qquan.mall.service.MallProductService;
import com.qqtech.qquan.mall.service.MallShopService;
import com.qqtech.qquan.mall.service.MallSupplierService;
import com.qqtech.qquan.mall.service.MallSupplierUserService;
import com.qqtech.qquan.order.cache.OrderSysParamCache;
import com.qqtech.qquan.order.dao.OrderBaseDao;
import com.qqtech.qquan.order.enums.OrderBaseCommentStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseDeliveryStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseDeliveryStatusSignTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderStatusCancelTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderBasePayStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBasePayTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseReturnPayStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseReturnStatusCompleteTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseReturnStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseSendDeliveryStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseSubsidyTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderConst;
import com.qqtech.qquan.order.enums.OrderDeliverySendDeliveryTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderDeliveryTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderPayWayDictEnum;
import com.qqtech.qquan.order.enums.OrderSplitTypeEnum;
import com.qqtech.qquan.order.enums.ReturnPayStatusAgreeTypeEnum;
import com.qqtech.qquan.order.model.OrderBase;
import com.qqtech.qquan.order.model.OrderBaseQuery;
import com.qqtech.qquan.order.model.OrderBaseVo;
import com.qqtech.qquan.order.model.OrderCouponQuery;
import com.qqtech.qquan.order.model.OrderDelivery;
import com.qqtech.qquan.order.model.OrderItem;
import com.qqtech.qquan.order.model.OrderPayLog;
import com.qqtech.qquan.order.model.OrderSplit;
import com.qqtech.qquan.push.service.PushBizzService;
import com.qqtech.qquan.send.cache.SendDeliverySysParamCache;
import com.qqtech.qquan.send.enums.SendConst;
import com.qqtech.qquan.send.enums.SendDeliveryOrderPickupStatusDictEnum;
import com.qqtech.qquan.send.enums.SendDeliveryOrderStatusDictEnum;
import com.qqtech.qquan.send.model.SendDeliveryOrderVo;
import com.qqtech.qquan.send.model.SendDeliveryUserOrder;
import com.qqtech.qquan.send.service.SendDeliveryOrderService;
import com.qqtech.qquan.send.service.SendDeliveryUserOrderService;
import com.qqtech.qquan.sms.service.SmsBizzService;
import com.qqtech.qquan.user.enums.UserMoneyLogTypeDictEnum;
import com.qqtech.qquan.user.model.UserBase;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.user.service.UserMoneyLogService;

@Service
public class OrderHandleServiceImpl extends BaseServiceImpl<OrderBase> implements OrderHandleService {
	public static final Logger log = LoggerFactory.getLogger(OrderHandleServiceImpl.class);

	@Resource
	private OrderSysParamCache orderSysParamCache;
	@Resource
	private OrderDeliveryService orderDeliveryService;
	@Resource
	private OrderItemService orderItemService;
	@Resource
	private OrderPayLogService orderPayLogService;
	@Resource
	private OrderBaseDao orderBaseDao;
	@Resource
	private HomemakingOrderService homemakingOrderService;
	@Resource
	private UserMoneyLogService userMoneyLogService;

	@Resource
	private DeliveryOrderDao deliveryOrderDao;

	@Resource
	private ActivitySignService activitySignService;

	@Resource
	private ActivityBaseService activityBaseService;

	@Resource
	private IdleBaseService idleBaseService;
	@Resource
	private PushBizzService pushBizzService;
	@Resource
	private SmsBizzService smsBizzService;
	@Resource
	private MallProductService mallProductService;

	@Resource
	private SendDeliveryOrderService sendDeliveryOrderService;

	@Resource
	private OrderSplitService orderSplitService;

	@Resource
	private CommunityBaseService communityBaseService;

	@Resource
	private MallSupplierUserService mallSupplierUserService;
	@Resource
	private MallSupplierService mallSupplierService;
	@Resource
	private UserBaseService userBaseService;
	@Resource
	private OrderCouponService orderCouponService;
	@Resource
	private SendDeliveryUserOrderService sendDeliveryUserOrderService;
	@Resource
	private SendDeliverySysParamCache sendDeliverySysParamCache;
	@Resource
	private MallShopService mallShopService;
	@Resource
	private HiOrderService hiOrderService;

	@Override
	protected BaseDao<OrderBase> getBaseDao() {
		return orderBaseDao;
	}

	@Override
	public Result createOrder(OrderBase orderBase, OrderDelivery orderDelivery, List<OrderItem> listItem)
			throws OrderException {
		Result result = new Result();
		if (orderBase == null || orderDelivery == null || listItem == null) {
			throw new OrderException("订单数据不完整");
		}
		if (!OrderBaseOrderTypeDictEnum.isInScope(orderBase.getOrderType())) {
			throw new OrderException("订单类型不正确");
		}
		if (orderBase.getBuyerId() == null || orderBase.getBuyerId().intValue() == 0) {
			throw new OrderException("买家信息异常");
		}
		if (StringUtil.isBlank(orderDelivery.getConsignee()) || StringUtil.isBlank(orderDelivery.getPhone())
				|| StringUtil.isBlank(orderDelivery.getAddress())) {
			throw new OrderException("请完整填写联系人、手机号以及地址");
		}
		if (OrderBaseOrderTypeDictEnum.DELIVERY.getCode() != orderBase.getOrderType()) { // 不是代收代送的
			if (listItem == null || listItem.size() == 0) {
				throw new OrderException("订单数据不完整");
			}
			if (orderBase.getOrderType() != null
					&& orderBase.getOrderType() != OrderBaseOrderTypeDictEnum.QUANMALL.getCode()
					&& (orderBase.getSellerId() == null || orderBase.getSellerId().intValue() == 0)) {
				throw new OrderException("卖家信息异常");
			}
		}
		if (OrderBaseOrderTypeDictEnum.QUANMALL.getCode() == orderBase.getOrderType()
				|| OrderBaseOrderTypeDictEnum.IDLE.getCode() == orderBase.getOrderType()
				|| OrderBaseOrderTypeDictEnum.DELIVERY.getCode() == orderBase.getOrderType()
				|| OrderBaseOrderTypeDictEnum.QSHOP.getCode() == orderBase.getOrderType()
				|| OrderBaseOrderTypeDictEnum.HOMEMAKING.getCode() == orderBase.getOrderType()) {
			if (orderBase.getCommunityId() == null) {
				throw new OrderException("买家地址信息不完整，请重新编辑");
			}
		}
		Timestamp now = TimeUtil.now();
		String orderNo = this.genOrderNo(orderBase.getBuyerId().intValue());
		orderBase.setOrderNo(orderNo);
		String title = "订单商品";
		int itemSize = listItem.size();
		if (StringUtil.isBlank(orderBase.getTitle())) {
			for (OrderItem orderItem : listItem) {
				if (StringUtil.isNotBlank(orderItem.getName())) {
					title = orderItem.getName();
					if (itemSize > 1) {
						title = title + "等";
					}
					break;
				}
			}
			orderBase.setTitle(title);
		}
		orderBase.setOrderStatus(OrderBaseOrderStatusDictEnum.UNCOMPLETED.getCode());
		orderBase.setOrderStatusAt(now);
		orderBase.setPayStatus(OrderBasePayStatusDictEnum.UNPAYED.getCode());
		if (orderBase.getPayType() == null) {
			orderBase.setPayType(OrderBasePayTypeDictEnum.ONLINE.getCode());
		}
		orderBase.setPayStatusAt(now);
		if (orderBase.getDeliveryStatus() == null) {
			orderBase.setDeliveryStatus(OrderBaseDeliveryStatusDictEnum.UNSEND.getCode());
		}
		orderBase.setDeliveryStatusAt(now);
		orderBase.setReturnPayStatus(OrderBaseReturnPayStatusDictEnum.NONEED.getCode());
		orderBase.setReturnPayStatusAt(now);
		orderBase.setReturnStatus(OrderBaseReturnStatusDictEnum.NONEED.getCode());
		orderBase.setReturnStatusAt(now);
		orderBase.setIsCallBack(YesNoEnum.NO.getCode());
		orderBase.setCommentStatus(OrderBaseCommentStatusDictEnum.NONE.getCode());
		orderBase.setAutoExpireAt(
				TimeUtil.addMins(now, orderSysParamCache.getInt(OrderConst.DICTYPE_ORDER_ONLINE_PAY_AUTO_EXPIRE_MINS)));
		Timestamp autoReceiveAt = TimeUtil.addDays(now,
				orderSysParamCache.getInt(OrderConst.DICTYPE_ORDER_ONLINE_RECEIVE_AUTO_EXPIRE_DAYS, 7));
		if (orderBase.getOrderType() != null
				&& OrderBaseOrderTypeDictEnum.QSHOP.getCode() == orderBase.getOrderType().intValue()) {
			autoReceiveAt = TimeUtil.addDays(now,
					orderSysParamCache.getInt(OrderConst.DICTYPE_ORDER_ONLINE_QSHOP_RECEIVE_AUTO_EXPIRE_DAYS, 1));
		} else if (orderBase.getOrderType() != null
				&& OrderBaseOrderTypeDictEnum.HOMEMAKING.getCode() == orderBase.getOrderType().intValue()) {
			autoReceiveAt = TimeUtil.addHours(now,
					orderSysParamCache.getInt(OrderConst.DICTYPE_ORDER_ONLINE_HOMEMAKING_RECEIVE_AUTO_EXPIRE_HOURS, 4));
		} else {
			if (orderBase.getIsExternal() != null && YesNoEnum.NO.getCode() == orderBase.getIsExternal()) {
				autoReceiveAt = TimeUtil.addDays(now,
						orderSysParamCache.getInt(OrderConst.DICTYPE_ORDER_ONLINE_LOCAL_RECEIVE_AUTO_EXPIRE_DAYS, 1));
			} else {
				autoReceiveAt = TimeUtil.addDays(now,
						orderSysParamCache.getInt(OrderConst.DICTYPE_ORDER_ONLINE_RECEIVE_AUTO_EXPIRE_DAYS, 7));
			}
		}
		orderBase.setAutoReceiveAt(autoReceiveAt);
		orderBase.setAutoRefundAt(TimeUtil.addDays(now,
				orderSysParamCache.getInt(OrderConst.DICTYPE_ORDER_ONLINE_REFUND_AUTO_EXPIRE_DAYS)));
		if (orderBase.getRemark() == null) {
			orderBase.setRemark("");
		} else {
			orderBase.setRemark(orderBase.getRemark().trim());
		}
		orderBase.setSendDeliveryStatus(OrderBaseSendDeliveryStatusDictEnum.NOTDELIVERY.getCode());// 配送状态为待配送
		orderBaseDao.insert(orderBase);
		// 设置订单详情
		for (OrderItem orderItem : listItem) {
			orderItem.setOrderNo(orderNo);
			if (StringUtil.isBlank(orderItem.getName())) {
				orderItem.setName("");
			}
			if (StringUtil.isBlank(orderItem.getProductSpecName())) {
				orderItem.setProductSpecName("");
			}
			orderItem.setIsComment(YesNoEnum.NO.getCode());
		}
		orderItemService.insertInBatch(listItem);
		orderDelivery.setOrderNo(orderNo);
		if (orderDelivery.getType() == null) {
			if (OrderBaseOrderTypeDictEnum.HOMEMAKING.getCode() == orderBase.getOrderType()
					|| OrderBaseOrderTypeDictEnum.DELIVERY.getCode() == orderBase.getOrderType()) {
				orderDelivery.setType(OrderDeliveryTypeDictEnum.SELLERSERVICE.getCode());
			} else {
				orderDelivery.setType(OrderDeliveryTypeDictEnum.SELLERSEND.getCode());
			}
		}

		orderDeliveryService.insert(orderDelivery);
		// 短信提醒--针对非服务订单的货到付款订单
		if (OrderBaseOrderTypeDictEnum.HOMEMAKING.getCode() != orderBase.getOrderType()
				&& OrderBasePayTypeDictEnum.ONDELIVERY.getCode() == orderBase.getPayType()) {
			smsBizzService.orderPayedOrOndelivery(orderNo);
		}
		result.put("orderNo", orderNo);
		result.put("payStatus", orderBase.getPayStatus());
		result.put("payType", orderBase.getPayType());
		result.put("priceTotal", orderBase.getTotal());
		// 如果订单额等于0，则生成订单后马上执行付款状态
		if (orderBase.getTotal() == null || orderBase.getTotal().compareTo(BigDecimal.ZERO) == 0) {
			OrderPayLog orderPayLog = new OrderPayLog();
			orderPayLog.setOrderNo(orderNo);
			orderPayLog.setValue(BigDecimal.ZERO);
			orderPayLog.setPayWay(0);
			payOrder(orderPayLog);
		}
		return result;
	}

	/**
	 * 生成并返回订单号
	 * 
	 * @return
	 */
	private String genOrderNo(int userId) {
		DateTime inputTime = new DateTime(TimeUtil.now());
		String orderNo = "" + (inputTime.getYear() % 100 / 2 + 2) + (inputTime.getDayOfYear() + 100)
				+ (inputTime.getSecondOfDay() + 10000) + userId;
		return orderNo;
	}

	@Override
	public Result payOrder(OrderPayLog orderPayLog) {
		Result result = new Result();
		String orderNo = orderPayLog.getOrderNo();
		if (StringUtil.isBlank(orderNo)) {
			result.addErr("订单号不能为空");
			return result;
		}
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("订单不存在");
			return result;
		}
		boolean isZeroPay = false;
		BigDecimal value = orderPayLog.getValue();
		Integer payWay = orderPayLog.getPayWay();
		if ((value == null || value.compareTo(BigDecimal.ZERO) == 0) && (payWay == null || payWay.intValue() == 0)) {
			isZeroPay = true;
		}
		BigDecimal payed = orderPayLogService.getPayedByOrderNo(orderNo, null);
		if (isZeroPay == false && ((payed != null && payed.compareTo(orderBase.getTotal()) >= 0)
				|| OrderBasePayStatusDictEnum.PAYED.getCode() == orderBase.getPayStatus())) {
			result.addErr("订单已支付，请勿重复操作");
			return result;
		}
		if (isZeroPay == false) {
			orderPayLogService.insert(orderPayLog);
		}
		payed = orderPayLogService.getPayedByOrderNo(orderNo, null);
		if (payed.compareTo(orderBase.getTotal()) >= 0) {// 如果已支付的大于或等于订单总额，则状态改为已支付
			OrderBaseQuery updateOrder = new OrderBaseQuery();
			updateOrder.setId(orderBase.getId());
			updateOrder.setPayStatus(OrderBasePayStatusDictEnum.PAYED.getCode());
			updateOrder.setPayStatusAt(TimeUtil.now());
			updateOrder.setIsCallBack(YesNoEnum.YES.getCode());
			int i = orderBaseDao.updateOrderStatusToPayed(updateOrder);
			if (i <= 0) {
				throw new OrderException("订单已支付，不能重复支付");
			}
			if (BigDecimal.ZERO.compareTo(orderBase.getTotal()) == 0) {
				log.info("订单金额为0，订单状态已改为已支付");
				result.setMsg("订单金额为0，订单状态已改为已支付");
			} else {
				log.info("付款成功，且订单已改为已支付");
				result.setMsg("付款成功，且订单已改为已支付");
			}

			// 下单同时生成分账信息-start
			List<OrderSplit> listOrderSplit = new ArrayList<OrderSplit>();
			HashMap<String, OrderSplit> orderSplitMap = new HashMap<String, OrderSplit>();
			OrderSplit otherOrderSplit = new OrderSplit();
			otherOrderSplit.setOriginalValue(new BigDecimal(0));
			OrderItem orderItemNew = new OrderItem();
			orderItemNew.setOrderNo(orderNo);
			List<OrderItem> listItem = orderItemService.queryList(orderItemNew);
			MallShop mallShop = null;
			BigDecimal rate = new BigDecimal(1);
			for (OrderItem orderItem : listItem) {
				orderItem.setOrderNo(orderNo);
				if (StringUtil.isBlank(orderItem.getName())) {
					orderItem.setName("");
				}
				if (StringUtil.isBlank(orderItem.getProductSpecName())) {
					orderItem.setProductSpecName("");
				}
				orderItem.setIsComment(YesNoEnum.NO.getCode());
				BigDecimal thisTotle = orderItem.getPrice().multiply(new BigDecimal(orderItem.getQuntity()));
				// 如果是直供商城(外部供应商)，则启用多供应商的分账
				if (OrderBaseOrderTypeDictEnum.QUANMALL.getCode() == orderBase.getOrderType()) {
					// 根据产品获取其供应商信息
					MallSupplierUser mallSupplierUser = new MallSupplierUser();
					mallSupplierUser.setSupplierId(orderItem.getSupplierId());
					List<MallSupplierUser> mallSupplierUserList = mallSupplierUserService.queryList(mallSupplierUser);
					if (mallSupplierUserList != null && mallSupplierUserList.size() > 0) {
						mallSupplierUser = mallSupplierUserList.get(0);
					} else {
						mallSupplierUser = null;
					}
					if (mallSupplierUser != null && mallSupplierUser.getSupplierId() != null) {
						MallSupplier mallSupplier = mallSupplierService.getById(mallSupplierUser.getSupplierId());
						UserBase userBase = userBaseService.getById(mallSupplierUser.getUserId());
						if (mallSupplier != null) {
							rate = new BigDecimal(1);
							if (mallSupplier.getRate() != null
									&& mallSupplier.getRate().compareTo(BigDecimal.ZERO) == 1) {
								rate = mallSupplier.getRate();
							}
							OrderSplit oldOrderSplit = orderSplitMap.get("" + mallSupplier.getId());
							if (oldOrderSplit != null) {
								oldOrderSplit.setRate(rate);
								oldOrderSplit.setOriginalValue(oldOrderSplit.getOriginalValue().add(thisTotle));
								oldOrderSplit.setValue(oldOrderSplit.getOriginalValue().multiply(rate));
								oldOrderSplit.setType(OrderSplitTypeEnum.PRODUCT.getCode());
								orderSplitMap.remove("" + mallSupplier.getId());
								orderSplitMap.put("" + mallSupplier.getId(), oldOrderSplit);
							} else {
								OrderSplit newOrderSplit = new OrderSplit();
								newOrderSplit.setOrderNo(orderNo);
								newOrderSplit.setSupplierId(mallSupplier.getId());
								newOrderSplit.setSupplierName(mallSupplier.getShortName());
								if (userBase != null) {
									newOrderSplit.setSellerId(userBase.getId());
								}
								newOrderSplit.setRate(rate);
								newOrderSplit.setOriginalValue(thisTotle);
								newOrderSplit.setValue(thisTotle.multiply(rate));
								newOrderSplit.setStatus(YesNoEnum.NO.getCode());
								newOrderSplit.setType(OrderSplitTypeEnum.PRODUCT.getCode());
								orderSplitMap.put("" + mallSupplier.getId(), newOrderSplit);
							}
						}
					}
				} else if (OrderBaseOrderTypeDictEnum.QSHOP.getCode() == orderBase.getOrderType()) {
					// 圈商(邻里购和本地商家)(兼容可以多个圈商产品同时下一个订单的模式，虽然当前前台只支持一个店铺下一个单)
					if (orderItem.getSupplierId() != null && orderItem.getSupplierId().intValue() != 0) {
						mallShop = mallShopService.getById(orderItem.getSupplierId());
						if (mallShop != null) {
							if (mallShop.getRate() != null && mallShop.getRate().compareTo(BigDecimal.ZERO) == 1) {
								rate = mallShop.getRate();
							}
							OrderSplit oldOrderSplit = orderSplitMap.get("" + mallShop.getId());
							if (oldOrderSplit != null) {
								oldOrderSplit.setRate(rate);
								oldOrderSplit.setOriginalValue(oldOrderSplit.getOriginalValue().add(thisTotle));
								oldOrderSplit.setValue(oldOrderSplit.getOriginalValue().multiply(rate));
								oldOrderSplit.setType(OrderSplitTypeEnum.PRODUCT.getCode());
								orderSplitMap.remove("" + mallShop.getId());
								orderSplitMap.put("" + mallShop.getId(), oldOrderSplit);
							} else {
								OrderSplit newOrderSplit = new OrderSplit();
								newOrderSplit.setOrderNo(orderNo);
								newOrderSplit.setSupplierId(mallShop.getId());
								newOrderSplit.setSupplierName(mallShop.getName());
								if (mallShop.getCreatorId() != null && mallShop.getCreatorId().intValue() != 0) {
									newOrderSplit.setSellerId(mallShop.getCreatorId());
								} else if (orderBase.getSellerId() != null) {
									newOrderSplit.setSellerId(orderBase.getSellerId());
								}
								newOrderSplit.setRate(rate);
								newOrderSplit.setOriginalValue(thisTotle);
								newOrderSplit.setValue(thisTotle.multiply(rate));
								newOrderSplit.setStatus(YesNoEnum.NO.getCode());
								newOrderSplit.setType(OrderSplitTypeEnum.PRODUCT.getCode());
								orderSplitMap.put("" + mallShop.getId(), newOrderSplit);
							}
						}
					}
				} else {
					// 非商城订单--start
					otherOrderSplit.setOrderNo(orderNo);
					otherOrderSplit.setSupplierId(null);
					otherOrderSplit.setSupplierName("");
					otherOrderSplit.setSellerId(orderBase.getSellerId());
					otherOrderSplit.setRate(new BigDecimal(1));
					otherOrderSplit.setOriginalValue(otherOrderSplit.getOriginalValue().add(thisTotle));
					otherOrderSplit.setValue(otherOrderSplit.getOriginalValue());
					otherOrderSplit.setStatus(YesNoEnum.NO.getCode());
					otherOrderSplit.setType(OrderSplitTypeEnum.PRODUCT.getCode());
					// 非商城订单--end
				}
			}
			OrderDelivery orderDelivery = orderDeliveryService.getByOrderNo(orderNo);
			if (mallShop != null && OrderBaseOrderTypeDictEnum.QSHOP.getCode() == orderBase.getOrderType()
					|| OrderBaseOrderTypeDictEnum.QUANMALL.getCode() == orderBase.getOrderType()) {
				if (!(orderSplitMap.isEmpty() || orderSplitMap.size() == 0)) {
					for (String key : orderSplitMap.keySet()) {
						listOrderSplit.add(orderSplitMap.get(key));
					}
				}
				if (mallShop != null && orderBase.getSubsidyType() != null
						&& orderBase.getSubsidyType().intValue() == OrderBaseSubsidyTypeDictEnum.SHOP.getCode()
						&& orderBase.getSubsidy() != null && orderBase.getSubsidy().compareTo(BigDecimal.ZERO) == 1) {
					// 如果商家有补贴，则扣除补贴的金额
					OrderSplit newOrderSplit = new OrderSplit();
					newOrderSplit.setOrderNo(orderNo);
					newOrderSplit.setSupplierId(mallShop.getId());
					newOrderSplit.setSupplierName(mallShop.getName());
					if (mallShop.getCreatorId() != null && mallShop.getCreatorId().intValue() != 0) {
						newOrderSplit.setSellerId(mallShop.getCreatorId());
					} else if (orderBase.getSellerId() != null) {
						newOrderSplit.setSellerId(orderBase.getSellerId());
					}
					if (rate == null) {
						rate = new BigDecimal(1);
					}
					newOrderSplit.setRate(rate);
					newOrderSplit.setOriginalValue(orderBase.getSubsidy());
					newOrderSplit.setValue(orderBase.getSubsidy().multiply(rate));
					newOrderSplit.setStatus(YesNoEnum.NO.getCode());
					newOrderSplit.setType(OrderSplitTypeEnum.SUBSIDY.getCode());
					listOrderSplit.add(newOrderSplit);
				}
				// 如果商家允许用户使用圈币等方式支付，相当于商家让利，也扣除这些让利金额
				BigDecimal shopDiscount = orderPayLogService.getShopDiscountByOrderNo(orderNo, null);
				if (shopDiscount != null && shopDiscount.compareTo(BigDecimal.ZERO) == 1) {
					OrderSplit newOrderSplitShop = new OrderSplit();
					newOrderSplitShop.setOrderNo(orderNo);
					newOrderSplitShop.setSupplierId(mallShop.getId());
					newOrderSplitShop.setSupplierName(mallShop.getName());
					if (mallShop.getCreatorId() != null && mallShop.getCreatorId().intValue() != 0) {
						newOrderSplitShop.setSellerId(mallShop.getCreatorId());
					} else if (orderBase.getSellerId() != null) {
						newOrderSplitShop.setSellerId(orderBase.getSellerId());
					}
					if (rate == null) {
						rate = new BigDecimal(1);
					}
					newOrderSplitShop.setRate(rate);
					newOrderSplitShop.setOriginalValue(shopDiscount);
					newOrderSplitShop.setValue(newOrderSplitShop.getOriginalValue().multiply(rate));
					newOrderSplitShop.setStatus(YesNoEnum.NO.getCode());
					newOrderSplitShop.setType(OrderSplitTypeEnum.SHOPDISCOUNT.getCode());
					listOrderSplit.add(newOrderSplitShop);
				}
				// 如果有配送费，则加上配送费
				if (mallShop != null && orderDelivery.getType() != null
						&& OrderDeliveryTypeDictEnum.SELLERSEND.getCode() == orderDelivery.getType()
						&& (orderDelivery.getHasNeedDelivery() == null
								|| YesNoEnum.NO.getCode() == orderDelivery.getHasNeedDelivery())
						&& orderDelivery.getSendDeliveryType() != null
						&& OrderDeliveryTypeDictEnum.SELLERSEND.getCode() == orderDelivery.getSendDeliveryType()) {
					if (orderDelivery.getFreight() != null
							&& orderDelivery.getFreight().compareTo(BigDecimal.ZERO) == 1) {
						OrderSplit newOrderSplit = new OrderSplit();
						newOrderSplit.setOrderNo(orderNo);
						newOrderSplit.setSupplierId(mallShop.getId());
						newOrderSplit.setSupplierName(mallShop.getName());
						if (mallShop.getCreatorId() != null && mallShop.getCreatorId().intValue() != 0) {
							newOrderSplit.setSellerId(mallShop.getCreatorId());
						} else if (orderBase.getSellerId() != null) {
							newOrderSplit.setSellerId(orderBase.getSellerId());
						}
						newOrderSplit.setRate(new BigDecimal(1));
						newOrderSplit.setOriginalValue(orderDelivery.getFreight());
						newOrderSplit.setValue(orderDelivery.getFreight());
						newOrderSplit.setStatus(YesNoEnum.NO.getCode());
						newOrderSplit.setType(OrderSplitTypeEnum.DELIVERY.getCode());
						listOrderSplit.add(newOrderSplit);
					}
				}
			} else {
				listOrderSplit.add(otherOrderSplit);
			}
			if (listOrderSplit != null && listOrderSplit.size() > 0) {
				orderSplitService.insertInBatch(listOrderSplit);
			}
			// 下单同时生成分账信息-end
			if (orderDelivery != null && orderDelivery.getType() != null
					&& orderDelivery.getType().intValue() == OrderDeliveryTypeDictEnum.BUYERPICKUP.getCode()) {
				// 自提的，发货状态改为已发货
				updateOrder.setDeliveryStatus(OrderBaseDeliveryStatusDictEnum.SENDED.getCode());
				updateOrder.setDeliveryStatusAt(updateOrder.getPayStatusAt());
				orderBaseDao.updateById(updateOrder);
				// 买家自提签收[这里不自动签收，店主扫码：订单二维码，再执行签收]
				// result = this.buyerPickUpAutoSign(orderNo);
			} else {
				smsBizzService.orderPayedOrOndelivery(orderNo);
			}
			pushBizzService.orderPayed(orderNo);
		} else {
			log.info("付款成功，但订单还未完全支付");
			result.setMsg("付款成功，但订单还未完全支付");
		}
		return result;
	}

	/**
	 * 逾期取消订单的公共业务
	 * 
	 * @param orderNo
	 * @param orderBaseOrderStatusDictEnum
	 * @return
	 */
	@Override
	public Result cancelBizz(String orderNo,
			OrderBaseOrderStatusCancelTypeDictEnum orderBaseOrderStatusCancelTypeDictEnum) {
		Result result = new Result();
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("订单有误");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.COMPLETED.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已完成，不能取消");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已经取消了，不能重复取消");
			return result;
		}

		if (OrderBaseOrderTypeDictEnum.HOMEMAKING.getCode() == orderBase.getOrderType()) { // 家政服务
			if (orderBaseOrderStatusCancelTypeDictEnum.getCode() == OrderBaseOrderStatusCancelTypeDictEnum.SELLERCANCEL
					.getCode()) {
				result = homemakingOrderService.handleCancelOrderBySeller(orderNo);
			} else {
				result = homemakingOrderService.handleCancelOrder(orderNo);
			}
			if (!result.checkForm()) {
				return result;
			}
		}
		if (OrderBaseOrderTypeDictEnum.ACTIVITY.getCode() == orderBase.getOrderType()) { // 活动订单
			ActivitySignVo activitySignVo = activitySignService.getSignByOrderNo(orderBase.getOrderNo());
			if (null != activitySignVo) {
				ActivityBaseVo activityBaseVo = activityBaseService.getById(activitySignVo.getActivityId());
				if (TimeUtil.now().after(activityBaseVo.getSignEndAt())) {// 超过报名截止时间
					result.addErr("该活动已经截止报名，不能取消。");
					return result;
				}
				activitySignService.handleCancle(activitySignVo.getUserId(), activitySignVo.getActivityId());// 删除报名记录
			}
		}
		if (OrderBaseOrderTypeDictEnum.IDLE.getCode() == orderBase.getOrderType()) {// 闲置品
			List<OrderItem> orderItemList = orderItemService.findByOrderNo(orderBase.getOrderNo());
			if (null != orderItemList && orderItemList.size() > 0) {
				idleBaseService.handleCancle(orderItemList.get(0).getProductId());
			}
		}
		OrderCouponQuery orderCouponQuery = new OrderCouponQuery();
		orderCouponQuery.setOrderNo(orderNo);
		int orderCouponCount = orderCouponService.queryCount(orderCouponQuery);
		if (orderCouponCount > 0) {// 优惠卷
			orderCouponService.handleCancle(orderNo);
		}

		Timestamp now = TimeUtil.now();
		OrderBaseQuery newOrderBase = new OrderBaseQuery();
		newOrderBase.setId(orderBase.getId());
		newOrderBase.setOrderStatus(OrderBaseOrderStatusDictEnum.CANCEL.getCode());
		newOrderBase.setOrderStatusCancelType(orderBaseOrderStatusCancelTypeDictEnum.getCode());
		newOrderBase.setOrderStatusAt(now);
		BigDecimal payed = orderPayLogService.getPayedByOrderNo(orderNo, null);
		BigDecimal payedGiven = orderPayLogService.getPayedByOrderNo(orderNo, OrderPayWayDictEnum.QUAN);
		payed = payed.subtract(payedGiven);
		// 买家取消时，服务X个小时外取消订单全额退款，X个小时内取消订单退款50%，开始服务时取消订单不给退款
		if (orderBaseOrderStatusCancelTypeDictEnum.getCode() != OrderBaseOrderStatusCancelTypeDictEnum.SELLERCANCEL
				.getCode()) {
			if (result.getMap().containsKey("returnPercent")) {
				double returnPercent = (double) result.get("returnPercent");
				if (returnPercent >= 0) {
					if (payed != null) {
						payed = payed.multiply(new BigDecimal(returnPercent));
					}
					if (payedGiven != null) {
						payedGiven = payedGiven.multiply(new BigDecimal(returnPercent));
					}
				}
			}
		}
		int updateCount = orderBaseDao.updateOrderStatusToCancle(newOrderBase);
		if (updateCount <= 0) {
			throw new OrderException("不能重复取消订单");
		}
		ReturnPayStatusAgreeTypeEnum returnPayStatusAgreeType = ReturnPayStatusAgreeTypeEnum.SELLER;
		String returnPayTips = "买家";
		if (orderBaseOrderStatusCancelTypeDictEnum.getCode() == OrderBaseOrderStatusCancelTypeDictEnum.SELLERCANCEL
				.getCode()) {
			returnPayStatusAgreeType = ReturnPayStatusAgreeTypeEnum.SELLER;
			returnPayTips = "卖家";
		} else if (orderBaseOrderStatusCancelTypeDictEnum
				.getCode() == OrderBaseOrderStatusCancelTypeDictEnum.ADMINCANCEL.getCode()) {
			returnPayStatusAgreeType = ReturnPayStatusAgreeTypeEnum.ADMIN;
			returnPayTips = "圈圈平台";
		}
		OrderBaseQuery newOrderBaseOther = new OrderBaseQuery();
		newOrderBaseOther.setId(orderBase.getId());
		if ((payed != null && payed.compareTo(BigDecimal.ZERO) == 1)
				|| (payedGiven != null && payedGiven.compareTo(BigDecimal.ZERO) == 1)) {
			newOrderBaseOther.setReturnPayStatus(OrderBaseReturnPayStatusDictEnum.RETURNED.getCode());
			// newOrderBaseOther.setReturnPayStatusAt(now);
			newOrderBaseOther.setReturnPayStatusAgreeType(returnPayStatusAgreeType.getCode());
			int i = orderBaseDao.updateReturnPayStatus(newOrderBaseOther);
			if (i <= 0) {
				throw new OrderException("不能重复退款");
			}
			// 取消订单，如已付款，则直接把款项退到用户的APP账户余额
			if (orderBase.getBuyerId() != null) {
				if (payed != null && payed.compareTo(BigDecimal.ZERO) == 1) {
					userMoneyLogService.addMoneyToUser(orderBase.getBuyerId(),
							new Double(ArithUtil
									.roundMoney(payed.multiply(new BigDecimal(CoreConst.VALUE_CORE_MONEYRATE))))
											.intValue(),
							returnPayTips + "取消订单" + orderNo + "，并退款到用户余额", UserMoneyLogTypeDictEnum.MONEY);
				}
				if (payedGiven != null && payedGiven.compareTo(BigDecimal.ZERO) == 1) {
					userMoneyLogService.addMoneyToUser(orderBase.getBuyerId(),
							new Double(ArithUtil
									.roundMoney(payedGiven.multiply(new BigDecimal(CoreConst.VALUE_CORE_MONEYRATE))))
											.intValue(),
							returnPayTips + "取消订单" + orderNo + "，并退款到圈币", UserMoneyLogTypeDictEnum.QUAN);
				}
				result.setMsg(returnPayTips + "取消订单，并退款到用户余额");
			}
		}
		String msg = returnPayTips + "已取消订单";
		if (OrderBasePayStatusDictEnum.PAYED.getCode() == orderBase.getPayStatus().intValue()) {
			msg = returnPayTips + "订单已取消，并退款到用户余额";
		}
		result.setMsg(msg);
		return result;
	}

	@Override
	public void autoCancelBeforePay() {
		Result result = new Result();
		OrderBase orderBase = new OrderBase();
		orderBase.setOrderStatus(OrderBaseOrderStatusDictEnum.UNCOMPLETED.getCode());
		orderBase.setPayStatus(OrderBasePayStatusDictEnum.UNPAYED.getCode());
		orderBase.setPayType(OrderBasePayTypeDictEnum.ONLINE.getCode());
		List<OrderBase> orderBaseList = this.orderBaseDao.queryList(orderBase);
		if (orderBaseList != null && orderBaseList.size() > 0) {
			for (OrderBase toDoOrder : orderBaseList) {
				if (toDoOrder.getAutoExpireAt() == null || TimeUtil.now().before(toDoOrder.getAutoExpireAt())) {
					continue;
				}
				if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == toDoOrder.getOrderStatus().intValue()) {
					result.addErr("该订单已取消");
					return;
				}
				/*
				 * if (OrderBaseDeliveryStatusDictEnum.SENDED.getCode() ==
				 * toDoOrder.getDeliveryStatus().intValue()) {
				 * result.addErr("卖家已发货，您可以申请退货"); return; }
				 */
				if (OrderBaseDeliveryStatusDictEnum.SIGNED.getCode() == toDoOrder.getDeliveryStatus().intValue()) {
					result.addErr("已签收，不能取消");
					return;
				}
				if (OrderBasePayTypeDictEnum.ONLINE.getCode() != toDoOrder.getPayType().intValue()
						|| OrderBasePayStatusDictEnum.UNPAYED.getCode() != toDoOrder.getPayStatus()) {
					result.addErr("非在线付款订单或者该订单不是未付款状态");
					return;
				}
				result = cancelBizz(toDoOrder.getOrderNo(), OrderBaseOrderStatusCancelTypeDictEnum.AUTO);
				if (result.checkForm()) {
					pushBizzService.orderCancel(toDoOrder.getOrderNo(), OrderBaseOrderStatusCancelTypeDictEnum.AUTO);
				}
			}
		}
	}

	@Override
	public Result buyerCancel(String orderNo) {
		Result result = new Result();
		if (StringUtil.isBlank(orderNo)) {
			result.addErr("订单号不能为空");
			return result;
		}
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("订单不存在");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已取消");
			return result;
		}

		/*
		 * if (orderBase.getIsExternal() != null && YesNoEnum.YES.getCode() ==
		 * orderBase.getIsExternal() &&
		 * OrderBaseDeliveryStatusDictEnum.SENDED.getCode() ==
		 * orderBase.getDeliveryStatus().intValue()) {
		 * result.addErr("卖家已发货，您可以申请退货"); return result; }
		 */
		if (orderBase.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QSHOP.getCode()
				|| orderBase.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QUANMALL.getCode()) {
			if (orderBase.getPayStatus().intValue() == OrderBasePayStatusDictEnum.PAYED.getCode()) {
				result.addErr("您已付款，需要申请退款");
			}
		}

		if (OrderBaseDeliveryStatusDictEnum.SIGNED.getCode() == orderBase.getDeliveryStatus().intValue()) {
			result.addErr("您已签收，不能取消");
			return result;
		}
		result = cancelBizz(orderNo, OrderBaseOrderStatusCancelTypeDictEnum.BUYERCANCEL);
		if (result.checkForm()) {
			pushBizzService.orderCancel(orderNo, OrderBaseOrderStatusCancelTypeDictEnum.BUYERCANCEL);
			smsBizzService.buyerCancel(orderNo);
		}
		return result;
	}

	@Override
	public Result sellerCancel(String orderNo) {
		Result result = new Result();
		if (StringUtil.isBlank(orderNo)) {
			result.addErr("订单号不能为空");
			return result;
		}
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("订单不存在");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已取消");
			return result;
		}
		if (OrderBaseDeliveryStatusDictEnum.SIGNED.getCode() == orderBase.getDeliveryStatus().intValue()) {
			result.addErr("订单已被买家签收，不能取消");
			return result;
		}
		return cancelBizz(orderNo, OrderBaseOrderStatusCancelTypeDictEnum.SELLERCANCEL);
	}

	@Override
	public Result adminCancel(String orderNo) {
		Result result = new Result();
		if (StringUtil.isBlank(orderNo)) {
			result.addErr("订单号不能为空");
			return result;
		}
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("订单不存在");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已取消");
			return result;
		}
		if (OrderBaseDeliveryStatusDictEnum.SIGNED.getCode() == orderBase.getDeliveryStatus().intValue()) {
			result.addErr("订单已被买家签收，不能取消");
			return result;
		}
		return cancelBizz(orderNo, OrderBaseOrderStatusCancelTypeDictEnum.ADMINCANCEL);
	}

	@Override
	public Result sended(String orderNo, Integer hasNeedDelivery, Integer sendDeliveryType, String deliveryName,
			String deliveryNo) {
		Result result = new Result();
		if (StringUtil.isBlank(orderNo)) {
			result.addErr("订单号不能为空");
			return result;
		}
		if (hasNeedDelivery == null) {
			result.addErr("hasNeedDelivery参数不能为空");
			return result;
		} else if (hasNeedDelivery.intValue() == YesNoEnum.NO.getCode() && sendDeliveryType == null) {
			result.addErr("sendDeliveryType参数不能为空");
			return result;
		} else if (hasNeedDelivery.intValue() == YesNoEnum.YES.getCode()) {
			if (StringUtil.isBlank(deliveryName) || StringUtil.isBlank(deliveryNo)) {
				result.addErr("物流信息不能为空");
				return result;
			}
		}
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("订单不存在");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已取消");
			return result;
		}
		if (OrderBasePayTypeDictEnum.ONLINE.getCode() == orderBase.getPayType()
				&& OrderBasePayStatusDictEnum.UNPAYED.getCode() == orderBase.getPayStatus().intValue()) {
			result.addErr("等待买家付款");
			return result;
		}
		if (OrderBaseReturnPayStatusDictEnum.RETURNING.getCode() == orderBase.getReturnPayStatus().intValue()) {
			result.addErr("买家正在申请退款，请及时处理");
			return result;
		}
		if (OrderBaseDeliveryStatusDictEnum.SENDED.getCode() == orderBase.getDeliveryStatus().intValue()) {
			result.addErr("订单已发货");
			return result;
		}
		OrderDelivery orderDeliveryUpdate = new OrderDelivery();
		OrderDelivery orderDelivery = orderDeliveryService.getByOrderNo(orderNo);
		if (orderDelivery == null) {
			result.addErr("订单号联系人信息有误");
			return result;
		}
		MallShop mallShop = null;
		if (hasNeedDelivery == YesNoEnum.YES.getCode()) { // 需要物流
			orderDeliveryUpdate.setDeliveryName(deliveryName);
			orderDeliveryUpdate.setDeliveryNo(deliveryNo);
		} else { // 不需要物流
			orderDeliveryUpdate.setSendDeliveryType(sendDeliveryType);// 设置配送类型
			if (sendDeliveryType.intValue() == OrderDeliverySendDeliveryTypeDictEnum.QUANQUAN.getCode()) {// 圈圈配送
				if (orderBase.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QSHOP.getCode()) {
					mallShop = mallShopService.getById(orderBase.getShopId());
					if (mallShop != null && mallShop.getType().intValue() == MallShopTypeDictEnum.QQMALLSHOP.getCode()
							&& mallShop.getStyle().intValue() == MallShopStyleDictEnum.VIRTUAL.getCode()) {
						result.addErr("邻里店类型的店铺不能使用圈圈配送！");
						return result;
					}
				}
				// 圈圈配送的需要生成配送单
				Result r = sendDeliveryOrderService.createSendDeliveryOrder(orderNo);
				if (r.checkForm()) {
					smsBizzService.orderPayedToSender(orderNo);
					smsBizzService.orderPayedToSuperSender(orderNo);
					pushBizzService.sendOrderWhenPayed(orderNo);
				}
			}
		}
		orderDeliveryUpdate.setId(orderDelivery.getId());
		orderDeliveryUpdate.setHasNeedDelivery(hasNeedDelivery);
		orderDeliveryService.updateById(orderDeliveryUpdate);
		Timestamp now = TimeUtil.now();
		OrderBaseQuery newOrderBase = new OrderBaseQuery();
		newOrderBase.setId(orderBase.getId());
		newOrderBase.setDeliveryStatusAt(now);
		// newOrderBase.setDeliveryStatus(OrderBaseDeliveryStatusDictEnum.SENDED.getCode());
		int i = orderBaseDao.updateOrderStatusToSended(newOrderBase);
		if (i <= 0) {
			throw new OrderException("不能重复发货");
		}
		pushBizzService.orderSent(orderNo);
		smsBizzService.orderSent(orderNo);
		return result;
	}

	/**
	 * 签收公共业务
	 * 
	 * @param orderNo
	 * @param orderBaseDeliveryStatusDictEnum
	 * @return
	 */
	@Override
	public Result signedBizz(String orderNo,
			OrderBaseDeliveryStatusSignTypeDictEnum orderBaseDeliveryStatusSignTypeDictEnum) {
		Result result = new Result();
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("该订单不存在");
			return result;
		}
		if (OrderBaseDeliveryStatusDictEnum.SIGNED.getCode() == orderBase.getDeliveryStatus()) {
			result.addErr("该订单已签收");
			return result;
		}
		if (OrderBaseOrderTypeDictEnum.HOMEMAKING.getCode() == orderBase.getOrderType()) {
			result = homemakingOrderService.handleConfirmService(orderNo);
			if (!result.checkForm()) {
				return result;
			}
		}
		Timestamp now = TimeUtil.now();
		OrderBaseQuery newOrderBase = new OrderBaseQuery();
		newOrderBase.setId(orderBase.getId());
		// newOrderBase.setOrderStatus(OrderBaseOrderStatusDictEnum.COMPLETED.getCode());
		newOrderBase.setOrderStatusAt(now);
		// newOrderBase.setDeliveryStatus(OrderBaseDeliveryStatusDictEnum.SIGNED.getCode());
		// newOrderBase.setDeliveryStatusAt(now);只记录发货时间，签收时间即订单完成时间
		newOrderBase.setDeliveryStatusSignType(orderBaseDeliveryStatusSignTypeDictEnum.getCode());
		int i = orderBaseDao.updateOrderStatusToSigned(newOrderBase);
		if (i <= 0) {
			throw new OrderException("不能重复签收订单");
		}
		// 货到付款的 把未付款的设为已付款
		if (OrderBasePayTypeDictEnum.ONDELIVERY.getCode() == orderBase.getPayType()
				&& OrderBasePayStatusDictEnum.UNPAYED.getCode() == orderBase.getPayStatus().intValue()) {
			OrderBase newOrderBaseOther = new OrderBase();
			newOrderBaseOther.setId(orderBase.getId());
			newOrderBaseOther.setPayStatus(OrderBasePayStatusDictEnum.PAYED.getCode());
			newOrderBaseOther.setPayStatusAt(now);
			orderBaseDao.updateById(newOrderBaseOther);
		}
		if (orderBaseDeliveryStatusSignTypeDictEnum.getCode() == OrderBaseDeliveryStatusSignTypeDictEnum.BUYERSIGNED
				.getCode()) {
			result.setMsg("买家签收订单");
		}
		// 订单签收，款项打给账户余额--start
		if (OrderBasePayTypeDictEnum.ONLINE.getCode() == orderBase.getPayType()) {
			// todo 从分账单中把对应对单的供应商实际金额转到供应商账户余额
			OrderSplit orderSplit = new OrderSplit();
			orderSplit.setOrderNo(orderNo);
			List<OrderSplit> orderSplitList = orderSplitService.queryList(orderSplit);
			BigDecimal sellerTotal = BigDecimal.ZERO;
			if (orderSplitList != null && orderSplitList.size() > 0) {
				String tips = "订单(" + orderNo + ")完成，卖家产品交易收入";
				for (OrderSplit orderSplit2 : orderSplitList) {
					BigDecimal bv = orderSplit2.getValue();
					if (orderSplit2.getSellerId() != null && orderSplit2.getSellerId().intValue() != 0 && bv != null
							&& bv.compareTo(BigDecimal.ZERO) == 1) {
						if (orderSplit2.getType() != null) {
							if (OrderSplitTypeEnum.DELIVERY.getCode() == orderSplit2.getType().intValue()) {
								tips = "订单(" + orderNo + ")完成，卖家运费收入";
							} else if (OrderSplitTypeEnum.SUBSIDY.getCode() == orderSplit2.getType().intValue()) {
								tips = "订单(" + orderNo + ")完成，扣除卖家补贴金额";
								bv = BigDecimal.ZERO.subtract(bv);
							} else if (OrderSplitTypeEnum.SHOPDISCOUNT.getCode() == orderSplit2.getType().intValue()) {
								tips = "订单(" + orderNo + ")完成，扣除卖家允许用户使用圈币消费抵扣";
								bv = BigDecimal.ZERO.subtract(bv);
							}
						}
						// 买家签收订单，订单金额已转到卖家余额
						userMoneyLogService.addMoneyToUser(orderSplit2.getSellerId(),
								new Double(ArithUtil
										.roundMoney(bv.multiply(new BigDecimal(CoreConst.VALUE_CORE_MONEYRATE))))
												.intValue(),
								tips, UserMoneyLogTypeDictEnum.MONEY);
						// 同时修改分账记录
						OrderSplit orderSplitNew = new OrderSplit();
						orderSplitNew.setId(orderSplit2.getId());
						orderSplitNew.setStatus(YesNoEnum.YES.getCode());
						orderSplitService.updateById(orderSplitNew);
						sellerTotal = sellerTotal.add(bv);
					}
				}
			} else {// 兼容以前(没分账功能的时候)的商家模式
				if (orderBase.getSellerId() != null && orderBase.getSellerId().intValue() != 0
						&& orderBase.getTotal() != null && orderBase.getTotal().compareTo(BigDecimal.ZERO) == 1) {
					sellerTotal = orderBase.getTotal();
					userMoneyLogService.addMoneyToUser(orderBase.getSellerId(),
							new Double(ArithUtil.roundMoney(
									orderBase.getTotal().multiply(new BigDecimal(CoreConst.VALUE_CORE_MONEYRATE))))
											.intValue(),
							"订单(" + orderNo + ")完成，卖家交易收入", UserMoneyLogTypeDictEnum.MONEY);
				}
			}
			OrderBaseQuery orderBaseNew = new OrderBaseQuery();
			orderBaseNew.setId(orderBase.getId());
			orderBaseNew.setSellerTotal(sellerTotal);
			orderBaseDao.updateSellerTotalById(orderBaseNew);
			if (orderBaseDeliveryStatusSignTypeDictEnum.getCode() == OrderBaseDeliveryStatusSignTypeDictEnum.BUYERSIGNED
					.getCode()) {
				result.setMsg("买家签收订单，订单金额已转到卖家余额");
			} else {
				result.setMsg("订单金额已转到卖家余额");
			}
		}
		// 订单签收，款项打给账户余额--end
		if (OrderBaseOrderTypeDictEnum.DELIVERY.getCode() == orderBase.getOrderType()) { // 代收代送更新状态
			DeliveryOrderVo deliveryOrder = deliveryOrderDao.getByOrderNo(orderBase.getOrderNo());
			if (deliveryOrder != null) {
				deliveryOrder.setStatus(DeliveryOrderStatusDictEnum.Signed.getCode());
				deliveryOrder.setStatusAt(now);
				deliveryOrder.setUpdAt(now);
				deliveryOrderDao.updateById(deliveryOrder);
			}
		}
		// 商城商品销量属性修改
		if (OrderBaseOrderTypeDictEnum.QUANMALL.getCode() == orderBase.getOrderType().intValue()
				|| OrderBaseOrderTypeDictEnum.QSHOP.getCode() == orderBase.getOrderType().intValue()) {
			List<OrderItem> itemList = orderItemService.findByOrderNo(orderBase.getOrderNo());
			if (itemList != null && itemList.size() > 0) {
				for (OrderItem item : itemList) {
					MallProduct itemProduct = mallProductService.getProductBySpecId(item.getProductId());
					if (itemProduct != null) {
						MallProduct updateProduct = new MallProduct();
						updateProduct.setId(itemProduct.getId());
						updateProduct.setSaleCount(itemProduct.getSaleCount() + item.getQuntity());
						mallProductService.updateById(updateProduct);
					}
				}
			}

		}
		// 荣誉系统，完成签 收后，都会得到该单消费金额10％的荣誉值和10％的圈币。（限每日首单,仅商城）
		if (orderBase.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QUANMALL.getCode()) {
			hiOrderService.orderSigned(orderBase.getBuyerId(), orderBase.getId(), orderBase.getTotal());
		} else if (orderBase.getOrderType().intValue() == OrderBaseOrderTypeDictEnum.QSHOP.getCode()) {
			Integer shopId = orderBase.getShopId();
			if (shopId != null) {
				MallShop shop = mallShopService.getById(shopId);
				if (shop != null) {
					if (shop.getStyle() == MallShopStyleDictEnum.QQSTORE.getCode()) {
						// 如果是圈圈便利店
						hiOrderService.orderSigned4QqStore(orderBase.getBuyerId(), orderBase.getId(),
								orderBase.getTotal());
					}
				}
			}

		}
		mallShopService.addSaleOrderCount(orderBase.getShopId());// 店铺订单销量字段加1
		return result;
	}

	@Override
	public void autoSign() {
		Result result = new Result();
		OrderBase orderBase = new OrderBase();
		orderBase.setOrderStatus(OrderBaseOrderStatusDictEnum.UNCOMPLETED.getCode());
		orderBase.setPayStatus(OrderBasePayStatusDictEnum.PAYED.getCode());
		orderBase.setReturnPayStatus(OrderBaseReturnPayStatusDictEnum.NONEED.getCode());
		orderBase.setDeliveryStatus(OrderBaseDeliveryStatusDictEnum.SENDED.getCode());
		List<OrderBase> orderBaseList = this.orderBaseDao.queryList(orderBase);
		if (orderBaseList != null && orderBaseList.size() > 0) {
			for (OrderBase toDoOrder : orderBaseList) {
				if (toDoOrder.getAutoReceiveAt() == null || TimeUtil.now().before(toDoOrder.getAutoReceiveAt())) {
					continue;
				}
				if (orderBase == null) {
					result.addErr("订单不存在");
					return;
				}
				if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
					result.addErr("该订单已取消");
					return;
				}
				if (OrderBaseDeliveryStatusDictEnum.SENDED.getCode() != orderBase.getDeliveryStatus().intValue()) {
					result.addErr("订单未发货");
					return;
				}
				result = signedBizz(toDoOrder.getOrderNo(), OrderBaseDeliveryStatusSignTypeDictEnum.AUTOSIGNED);
				if (result.checkForm()) {
					pushBizzService.orderSigned(toDoOrder.getOrderNo(),
							OrderBaseDeliveryStatusSignTypeDictEnum.AUTOSIGNED);
					smsBizzService.orderSigned(toDoOrder.getOrderNo(),
							OrderBaseDeliveryStatusSignTypeDictEnum.AUTOSIGNED);
				}
			}
		}
	}

	@Override
	public Result signed(String orderNo) {
		Result result = new Result();
		if (StringUtil.isBlank(orderNo)) {
			result.addErr("订单号不能为空");
			return result;
		}
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("订单不存在");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已取消");
			return result;
		}
		if (OrderBaseDeliveryStatusDictEnum.SENDED.getCode() != orderBase.getDeliveryStatus().intValue()) {
			result.addErr("订单未发货");
			return result;
		}
		result = signedBizz(orderNo, OrderBaseDeliveryStatusSignTypeDictEnum.BUYERSIGNED);
		if (result.checkForm()) {
			pushBizzService.orderSigned(orderNo, OrderBaseDeliveryStatusSignTypeDictEnum.BUYERSIGNED);
			smsBizzService.orderSigned(orderNo, OrderBaseDeliveryStatusSignTypeDictEnum.BUYERSIGNED);
		}
		result.put("orderBase", orderBase);
		return result;
	}

	@Override
	public Result buyerPickUpAutoSign(String orderNo) {
		Result result = new Result();
		if (StringUtil.isBlank(orderNo)) {
			result.addErr("订单号不能为空");
			return result;
		}
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("订单不存在");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已取消");
			return result;
		}
		if (OrderBaseDeliveryStatusDictEnum.SENDED.getCode() != orderBase.getDeliveryStatus().intValue()) {
			result.addErr("订单未发货");
			return result;
		}
		result = signedBizz(orderNo, OrderBaseDeliveryStatusSignTypeDictEnum.BUYERPICKUP);
		if (result.checkForm()) {
			pushBizzService.orderSigned(orderNo, OrderBaseDeliveryStatusSignTypeDictEnum.BUYERPICKUP);
			smsBizzService.orderSigned(orderNo, OrderBaseDeliveryStatusSignTypeDictEnum.BUYERPICKUP);
		}
		return result;
	}

	@Override
	public Result applyReturn(OrderDelivery orderDelivery) {
		Result result = new Result();
		if (StringUtil.isBlank(orderDelivery.getOrderNo())) {
			result.addErr("订单号不能为空");
			return result;
		}
		if (StringUtil.isBlank(orderDelivery.getDeliveryName()) || StringUtil.isBlank(orderDelivery.getDeliveryNo())
				|| StringUtil.isBlank(orderDelivery.getDeliveryNo()) || StringUtil.isBlank(orderDelivery.getConsignee())
				|| StringUtil.isBlank(orderDelivery.getPhone()) || StringUtil.isBlank(orderDelivery.getAddress())) {
			result.addErr("物流关键信息不能为空");
			return result;
		}
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderDelivery.getOrderNo());
		if (orderBase == null) {
			result.addErr("订单不存在");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已取消");
			return result;
		}
		if (OrderBaseDeliveryStatusDictEnum.SENDED.getCode() != orderBase.getDeliveryStatus().intValue()) {
			result.addErr("订单未发货，您可以直接取消订单");
			return result;
		}
		orderDelivery.setType(OrderDeliveryTypeDictEnum.BUYERRETURN.getCode());
		orderDeliveryService.insert(orderDelivery);
		Timestamp now = TimeUtil.now();
		OrderBaseQuery newOrderBase = new OrderBaseQuery();
		newOrderBase.setId(orderBase.getId());
		newOrderBase.setReturnStatus(OrderBaseReturnStatusDictEnum.RETURNING.getCode());
		newOrderBase.setReturnStatusAt(now);
		int i = orderBaseDao.updateOrderReturnStatus(newOrderBase);
		if (i <= 0) {
			throw new OrderException("不能重复退货(退款)");
		}
		this.applyReturnPay(orderBase.getOrderNo());
		pushBizzService.applyReturn(orderBase.getOrderNo());
		smsBizzService.applyReturn(orderBase.getOrderNo());
		return result;
	}

	/**
	 * 退款退货公共业务
	 * 
	 * @param orderNo
	 * @param orderBaseReturnStatusDictEnum
	 * @return
	 */
	@Override
	public Result returnedBizz(String orderNo,
			OrderBaseReturnStatusCompleteTypeDictEnum orderBaseReturnStatusCompleteTypeDictEnum) {
		Result result = new Result();
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBaseReturnStatusCompleteTypeDictEnum == null) {
			orderBaseReturnStatusCompleteTypeDictEnum = OrderBaseReturnStatusCompleteTypeDictEnum.AUTORETURNED;
		}
		Timestamp now = TimeUtil.now();
		OrderBaseQuery newOrderBase = new OrderBaseQuery();
		newOrderBase.setId(orderBase.getId());
		newOrderBase.setReturnStatus(OrderBaseReturnStatusDictEnum.RETURNED.getCode());
		newOrderBase.setReturnStatusAt(now);
		newOrderBase.setReturnStatusCompleteType(orderBaseReturnStatusCompleteTypeDictEnum.getCode());
		int i = orderBaseDao.updateOrderReturnStatus(newOrderBase);
		if (i <= 0) {
			throw new OrderException("不能重复退货(退款)");
		}
		ReturnPayStatusAgreeTypeEnum returnPayStatusAgreeType = ReturnPayStatusAgreeTypeEnum.SELLER;
		String returnPayTips = "";
		if (orderBaseReturnStatusCompleteTypeDictEnum
				.getCode() != OrderBaseReturnStatusCompleteTypeDictEnum.SELLERRETURNED.getCode()) {
			returnPayStatusAgreeType = ReturnPayStatusAgreeTypeEnum.SELLER;
			returnPayTips = "卖家";
		} else if (orderBaseReturnStatusCompleteTypeDictEnum
				.getCode() != OrderBaseReturnStatusCompleteTypeDictEnum.AUTORETURNED.getCode()) {
			returnPayStatusAgreeType = ReturnPayStatusAgreeTypeEnum.ADMIN;
			returnPayTips = "圈圈平台";
		}
		this.agreeReturnPayBizz(orderNo, returnPayStatusAgreeType);
		if (orderBase.getTotal().compareTo(BigDecimal.ZERO) == 1) {
			BigDecimal payed = orderPayLogService.getPayedByOrderNo(orderNo, OrderPayWayDictEnum.MONEY);
			BigDecimal payedGiven = orderPayLogService.getPayedByOrderNo(orderNo, OrderPayWayDictEnum.QUAN);
			if (orderBase.getBuyerId() != null) {
				if (payed != null && payed.compareTo(BigDecimal.ZERO) == 1) {
					userMoneyLogService.addMoneyToUser(orderBase.getBuyerId(),
							new Double(ArithUtil
									.roundMoney(payed.multiply(new BigDecimal(CoreConst.VALUE_CORE_MONEYRATE))))
											.intValue(),
							returnPayTips + "已确认退货，并退款到买家余额", UserMoneyLogTypeDictEnum.MONEY);
				}
				if (payedGiven != null && payedGiven.compareTo(BigDecimal.ZERO) == 1) {
					userMoneyLogService.addMoneyToUser(orderBase.getBuyerId(),
							new Double(ArithUtil
									.roundMoney(payedGiven.multiply(new BigDecimal(CoreConst.VALUE_CORE_MONEYRATE))))
											.intValue(),
							returnPayTips + "已确认退货，并退款到买家圈币", UserMoneyLogTypeDictEnum.QUAN);
				}
				result.setMsg(returnPayTips + "已确认退货，并退款到买家余额");
			}
		}
		return result;
	}

	@Override
	public void autoReturned() {
		Result result = new Result();
		OrderBase orderBase = new OrderBase();
		orderBase.setReturnStatus(OrderBaseReturnStatusDictEnum.RETURNING.getCode());
		List<OrderBase> orderBaseList = this.orderBaseDao.queryList(orderBase);
		if (orderBaseList != null && orderBaseList.size() > 0) {
			for (OrderBase toDoOrder : orderBaseList) {
				if (toDoOrder.getAutoRefundAt() == null || TimeUtil.now().before(toDoOrder.getAutoRefundAt())) {
					continue;
				}
				if (orderBase == null) {
					result.addErr("订单不存在");
					return;
				}
				if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
					result.addErr("该订单已取消");
					return;
				}
				if (OrderBaseReturnStatusDictEnum.RETURNING.getCode() != orderBase.getReturnStatus().intValue()) {
					result.addErr("用户没有申请退货");
					return;
				}
				result = returnedBizz(toDoOrder.getOrderNo(), OrderBaseReturnStatusCompleteTypeDictEnum.AUTORETURNED);
				if (result.checkForm()) {
					pushBizzService.returned(toDoOrder.getOrderNo(),
							OrderBaseReturnStatusCompleteTypeDictEnum.AUTORETURNED);
					smsBizzService.returned(toDoOrder.getOrderNo(),
							OrderBaseReturnStatusCompleteTypeDictEnum.AUTORETURNED);
				}
			}
		}
	}

	@Override
	public Result returned(String orderNo) {
		Result result = new Result();
		if (StringUtil.isBlank(orderNo)) {
			result.addErr("订单号不能为空");
			return result;
		}
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("订单不存在");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已取消");
			return result;
		}
		if (OrderBaseReturnStatusDictEnum.RETURNING.getCode() != orderBase.getReturnStatus().intValue()) {
			result.addErr("用户没有申请退货");
			return result;
		}
		result = returnedBizz(orderNo, OrderBaseReturnStatusCompleteTypeDictEnum.SELLERRETURNED);
		if (result.checkForm()) {
			pushBizzService.returned(orderNo, OrderBaseReturnStatusCompleteTypeDictEnum.SELLERRETURNED);
			smsBizzService.returned(orderNo, OrderBaseReturnStatusCompleteTypeDictEnum.SELLERRETURNED);
		}
		return result;
	}

	@Override
	public Result deliveryed(OrderBaseVo orderBaseVo) {
		Result result = new Result();
		OrderBase orderBase = null;
		if (orderBaseVo == null) {
			result.addErr("参数不能为空");
		} else {
			if (StringUtil.isBlank(orderBaseVo.getOrderNo())) {
				result.addErr("订单号不能为空");
			} else {
				orderBase = this.orderBaseDao.getByOrderNo(orderBaseVo.getOrderNo());
				if (orderBase == null) {
					result.addErr("订单号不存在");
				} else if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
					result.addErr("该订单已取消");
				} else if (OrderBasePayTypeDictEnum.ONLINE.getCode() == orderBase.getPayType()
						&& OrderBasePayStatusDictEnum.UNPAYED.getCode() == orderBase.getPayStatus().intValue()) {
					result.addErr("等待买家付款");
				} else if (OrderBaseSendDeliveryStatusDictEnum.NOTDELIVERY.getCode() == orderBase
						.getSendDeliveryStatus().intValue()) {
					result.addErr("该订单还没有取件完");
				} else if (OrderBaseSendDeliveryStatusDictEnum.DELIVERYED.getCode() == orderBase.getSendDeliveryStatus()
						.intValue()) {
					result.addErr("该订单已经配送完");
				}
			}
			/*
			 * if (result.checkForm() && (orderBaseVo.getSendDeliveryOrderList()
			 * == null || orderBaseVo.getSendDeliveryOrderList().isEmpty())) {
			 * result.addErr("请勾选配送单"); }
			 */
		}
		if (result.checkForm()) {
			Timestamp now = TimeUtil.now();
			List<SendDeliveryOrderVo> sendDeliveryOrderListOld = sendDeliveryOrderService
					.findOnlyByOrderNo(orderBaseVo.getOrderNo());
			/*
			 * for (SendDeliveryOrderVo sdo :
			 * orderBaseVo.getSendDeliveryOrderList()) { for
			 * (SendDeliveryOrderVo old : sendDeliveryOrderListOld) { //
			 * 配送单里未配送的 更新为已配送 if (sdo.getId().intValue() == old.getId() &&
			 * old.getDeliveryStatus() .intValue() ==
			 * SendDeliveryOrderStatusDictEnum.NOTDELIVERY.getCode()) {
			 * SendDeliveryOrderVo update = new SendDeliveryOrderVo();
			 * update.setId(sdo.getId()); update.setDeliveryAt(now);
			 * update.setDeliveryStatus(SendDeliveryOrderStatusDictEnum.
			 * DELIVERYED.getCode());
			 * sendDeliveryOrderService.updateById(update);
			 * sendDeliveryOrderListOld.remove(old); break; } } } boolean flag =
			 * true;// 是否全部是已配送 if (sendDeliveryOrderListOld != null &&
			 * !sendDeliveryOrderListOld.isEmpty()) { for (SendDeliveryOrderVo
			 * old : sendDeliveryOrderListOld) { if
			 * (old.getDeliveryStatus().intValue() ==
			 * SendDeliveryOrderStatusDictEnum.NOTDELIVERY.getCode()) { flag =
			 * false; break; } } } OrderBase updateOrder = new OrderBase();
			 * updateOrder.setId(orderBase.getId());
			 * updateOrder.setSendDeliveryAt(now); if (flag) {
			 * updateOrder.setSendDeliveryStatus(
			 * OrderBaseSendDeliveryStatusDictEnum.DELIVERYED.getCode());
			 * orderBaseDao.updateById(updateOrder); result =
			 * signedBizz(orderBase.getOrderNo(),
			 * OrderBaseDeliveryStatusSignTypeDictEnum.AUTOSIGNED); } else {
			 * updateOrder.setSendDeliveryStatus(
			 * OrderBaseSendDeliveryStatusDictEnum.DELIVERYING.getCode());
			 * orderBaseDao.updateById(updateOrder); }
			 */
			for (SendDeliveryOrderVo old : sendDeliveryOrderListOld) {
				// 配送单里未配送的 更新为已配送
				if (old.getDeliveryStatus().intValue() == SendDeliveryOrderStatusDictEnum.NOTDELIVERY.getCode()) {
					SendDeliveryOrderVo update = new SendDeliveryOrderVo();
					update.setId(old.getId());
					update.setDeliveryAt(now);
					update.setDeliveryStatus(SendDeliveryOrderStatusDictEnum.DELIVERYED.getCode());
					sendDeliveryOrderService.updateById(update);
				}
			}
			OrderBase updateOrder = new OrderBase();
			updateOrder.setId(orderBase.getId());
			updateOrder.setSendDeliveryAt(now);
			updateOrder.setSendDeliveryStatus(OrderBaseSendDeliveryStatusDictEnum.DELIVERYED.getCode());
			orderBaseDao.updateById(updateOrder);
			signedBizz(orderBase.getOrderNo(), OrderBaseDeliveryStatusSignTypeDictEnum.SENDDELIVERYSIGNED);
			result.put("sendDeliveryStatus", updateOrder.getSendDeliveryStatus());
			// 配送费结算
			SendDeliveryUserOrder sendDeliveryUserOrder = sendDeliveryUserOrderService
					.getByOrderNo(orderBase.getOrderNo());
			if (sendDeliveryUserOrder != null && sendDeliveryUserOrder.getDeliveryUserId() != null) {
				int fee = sendDeliverySysParamCache.getInt(SendConst.PARAMKEY_SEND_DELIVERY_ORDER_FEE, 2);
				int needMins = sendDeliverySysParamCache.getInt(SendConst.PARAMKEY_SEND_DELIVERY_ORDER_NEEDTIME_MINS,
						40);
				String timeStr = "";
				int seconds = TimeUtil.secondsOfTwo(sendDeliveryUserOrder.getAssignedAt(), now);
				int m = seconds / 60;
				int s = seconds % 60;
				if (m > 0) {
					timeStr = timeStr + m + "分钟";
				}
				if (s > 0) {
					timeStr = timeStr + s + "秒";
				}
				String tab = "分钟外";
				if (seconds <= (needMins * 60)) {
					tab = "分钟内";
					fee = sendDeliverySysParamCache.getInt(SendConst.PARAMKEY_SEND_DELIVERY_ORDER_FEE1, 4);
				}
				userMoneyLogService.addMoneyToUser(sendDeliveryUserOrder.getDeliveryUserId(),
						new Double(fee * CoreConst.VALUE_CORE_MONEYRATE).intValue(),
						"订单(" + orderBase.getOrderNo() + ")配送进账，耗时" + timeStr + "(" + needMins + tab + ")",
						UserMoneyLogTypeDictEnum.MONEY);
			}
		}
		return result;
	}

	@Override
	public Result pickuped(OrderBaseVo orderBaseVo) {
		Result result = new Result();
		OrderBase orderBase = null;
		if (orderBaseVo == null) {
			result.addErr("参数不能为空");
		} else {
			if (StringUtil.isBlank(orderBaseVo.getOrderNo())) {
				result.addErr("订单号不能为空");
			} else {
				orderBase = this.orderBaseDao.getByOrderNo(orderBaseVo.getOrderNo());
				if (orderBase == null) {
					result.addErr("订单号不存在");
				} else if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
					result.addErr("该订单已取消");
				} else if (OrderBasePayTypeDictEnum.ONLINE.getCode() == orderBase.getPayType()
						&& OrderBasePayStatusDictEnum.UNPAYED.getCode() == orderBase.getPayStatus().intValue()) {
					result.addErr("等待买家付款");
				} else if (OrderBaseSendDeliveryStatusDictEnum.DELIVERYING.getCode() == orderBase
						.getSendDeliveryStatus().intValue()) {
					result.addErr("该订单已经配送中");
				} else if (OrderBaseSendDeliveryStatusDictEnum.DELIVERYED.getCode() == orderBase.getSendDeliveryStatus()
						.intValue()) {
					result.addErr("该订单已经配送完");
				}
			}
			if (result.checkForm() && (orderBaseVo.getSendDeliveryOrderList() == null
					|| orderBaseVo.getSendDeliveryOrderList().isEmpty())) {
				result.addErr("请勾选配送单");
			}
		}
		if (result.checkForm()) {
			Timestamp now = TimeUtil.now();
			List<SendDeliveryOrderVo> sendDeliveryOrderListOld = sendDeliveryOrderService
					.findOnlyByOrderNo(orderBaseVo.getOrderNo());
			for (SendDeliveryOrderVo sdo : orderBaseVo.getSendDeliveryOrderList()) {
				for (SendDeliveryOrderVo old : sendDeliveryOrderListOld) {
					// 配送单里未配送的 更新为已配送
					if (sdo.getId().intValue() == old.getId() && old.getPickupStatus()
							.intValue() == SendDeliveryOrderPickupStatusDictEnum.NOTPICKUP.getCode()) {
						SendDeliveryOrderVo update = new SendDeliveryOrderVo();
						update.setId(sdo.getId());
						update.setPickupStatus(SendDeliveryOrderPickupStatusDictEnum.PICKUPED.getCode());
						update.setPickupAt(now);
						sendDeliveryOrderService.updateById(update);
						sendDeliveryOrderListOld.remove(old);
						break;
					}
				}
			}
			boolean flag = true;// 是否全部是已取件
			if (sendDeliveryOrderListOld != null && !sendDeliveryOrderListOld.isEmpty()) {
				for (SendDeliveryOrderVo old : sendDeliveryOrderListOld) {
					if (old.getPickupStatus().intValue() == SendDeliveryOrderPickupStatusDictEnum.NOTPICKUP.getCode()) {
						flag = false;
						break;
					}
				}
			}
			int sendDeliveryStatus = OrderBaseSendDeliveryStatusDictEnum.NOTDELIVERY.getCode();
			if (flag) {
				// 全部取件 订单状态改为配送中
				OrderBase updateOrder = new OrderBase();
				updateOrder.setId(orderBase.getId());
				updateOrder.setSendDeliveryStatus(OrderBaseSendDeliveryStatusDictEnum.DELIVERYING.getCode());
				updateOrder.setSendDeliveryAt(now);
				orderBaseDao.updateById(updateOrder);
				sendDeliveryStatus = OrderBaseSendDeliveryStatusDictEnum.DELIVERYING.getCode();
			}
			result.put("sendDeliveryStatus", sendDeliveryStatus);
		}
		return result;
	}

	@Override
	public Result applyReturnPay(String orderNo) {
		Result result = new Result();
		if (StringUtil.isBlank(orderNo)) {
			result.addErr("订单号不能为空");
			return result;
		}
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("订单不存在");
			return result;
		}
		if (OrderBaseReturnPayStatusDictEnum.RETURNING.getCode() == orderBase.getReturnPayStatus().intValue()) {
			result.addErr("该订单在申请退款中");
			return result;
		}
		if (OrderBaseReturnPayStatusDictEnum.RETURNED.getCode() == orderBase.getReturnPayStatus().intValue()) {
			result.addErr("该订单已退款");
			return result;
		}
		if (OrderBasePayStatusDictEnum.UNPAYED.getCode() == orderBase.getPayStatus().intValue()) {
			result.addErr("该订单未付款");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已取消");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.DELETE.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已删除");
			return result;
		}
		Timestamp now = TimeUtil.now();
		OrderBaseQuery newOrderBase = new OrderBaseQuery();
		newOrderBase.setId(orderBase.getId());
		newOrderBase.setReturnPayStatus(OrderBaseReturnPayStatusDictEnum.RETURNING.getCode());
		newOrderBase.setReturnPayStatusAt(now);
		int i = orderBaseDao.updateReturnPayStatus(newOrderBase);
		if (i <= 0) {
			throw new OrderException("不能重复申请退款");
		}
		pushBizzService.applyReturnPay(orderBase.getOrderNo());
		smsBizzService.applyReturnPay(orderNo);
		return result;
	}

	@Override
	public Result agreeReturnPayBizz(String orderNo, ReturnPayStatusAgreeTypeEnum returnPayStatusAgreeTypeEnum) {
		Result result = new Result();
		if (StringUtil.isBlank(orderNo)) {
			result.addErr("订单号不能为空");
			return result;
		}
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("订单不存在");
			return result;
		}
		if (OrderBaseReturnPayStatusDictEnum.NONEED.getCode() == orderBase.getReturnPayStatus().intValue()) {
			result.addErr("该订单没申请退款");
			return result;
		}
		if (OrderBaseReturnPayStatusDictEnum.RETURNED.getCode() == orderBase.getReturnPayStatus().intValue()) {
			result.addErr("该订单已退款");
			return result;
		}
		if (OrderBaseReturnPayStatusDictEnum.REFUSE.getCode() == orderBase.getReturnPayStatus().intValue()) {
			result.addErr("该订单拒绝退款");
			return result;
		}
		if (OrderBasePayStatusDictEnum.UNPAYED.getCode() == orderBase.getPayStatus().intValue()) {
			result.addErr("该订单未付款");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已取消");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.DELETE.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已删除");
			return result;
		}
		OrderBaseOrderStatusCancelTypeDictEnum obosc = OrderBaseOrderStatusCancelTypeDictEnum.SELLERCANCEL;
		if (returnPayStatusAgreeTypeEnum == null) {
			returnPayStatusAgreeTypeEnum = ReturnPayStatusAgreeTypeEnum.SELLER;
		} else if (returnPayStatusAgreeTypeEnum.getCode() == ReturnPayStatusAgreeTypeEnum.ADMIN.getCode()) {
			obosc = OrderBaseOrderStatusCancelTypeDictEnum.ADMINCANCEL;
		}
		result = this.cancelBizz(orderNo, obosc);
		if (result.checkForm()) {
			pushBizzService.returnPayed(orderNo, returnPayStatusAgreeTypeEnum);
			smsBizzService.agreeReturnPay(orderNo, returnPayStatusAgreeTypeEnum);
		}
		return result;
	}

	@Override
	public Result sellerAgreeReturnPay(String orderNo) {
		return this.agreeReturnPayBizz(orderNo, ReturnPayStatusAgreeTypeEnum.SELLER);
	}

	@Override
	public Result adminAgreeReturnPay(String orderNo) {
		return this.agreeReturnPayBizz(orderNo, ReturnPayStatusAgreeTypeEnum.ADMIN);
	}

	@Override
	public Result sellerRefuseReturnPay(String orderNo) {
		Result result = new Result();
		if (StringUtil.isBlank(orderNo)) {
			result.addErr("订单号不能为空");
			return result;
		}
		OrderBase orderBase = this.orderBaseDao.getByOrderNo(orderNo);
		if (orderBase == null) {
			result.addErr("订单不存在");
			return result;
		}
		if (OrderBaseReturnPayStatusDictEnum.NONEED.getCode() == orderBase.getReturnPayStatus().intValue()) {
			result.addErr("该订单没申请退款");
			return result;
		}
		if (OrderBaseReturnPayStatusDictEnum.RETURNED.getCode() == orderBase.getReturnPayStatus().intValue()) {
			result.addErr("该订单已退款");
			return result;
		}
		if (OrderBaseReturnPayStatusDictEnum.REFUSE.getCode() == orderBase.getReturnPayStatus().intValue()) {
			result.addErr("该订单已拒绝退款");
			return result;
		}
		if (OrderBasePayStatusDictEnum.UNPAYED.getCode() == orderBase.getPayStatus().intValue()) {
			result.addErr("该订单未付款");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.CANCEL.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已取消");
			return result;
		}
		if (OrderBaseOrderStatusDictEnum.DELETE.getCode() == orderBase.getOrderStatus().intValue()) {
			result.addErr("该订单已删除");
			return result;
		}
		OrderBaseQuery newOrderBase = new OrderBaseQuery();
		newOrderBase.setId(orderBase.getId());
		newOrderBase.setReturnPayStatus(OrderBaseReturnPayStatusDictEnum.REFUSE.getCode());
		// newOrderBase.setReturnPayStatusAt(now);
		int i = orderBaseDao.updateReturnPayStatus(newOrderBase);
		if (i <= 0) {
			throw new OrderException("不能重复拒绝退款");
		}
		pushBizzService.refuseReturnPay(orderNo);
		smsBizzService.refuseReturnPay(orderNo);
		return result;
	}
}